package com.demo.common;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;





import org.apache.commons.lang3.StringUtils;

import util.EncryptUtil;
import util.GsonUtil;
import util.HttpUtils;
import util.ResultData;
import util.ResultDataUtil;
//import com.doraemoney.parent.loan.pojo.WeixinVo;

/**
 * @author ducongcong
 * @date 2016年5月24日
 */
public class WeixinUtils {

	/**
	 * 授权重定向链接
	 */
	public static String URL_OAUTH2_AUTHORIZE = "https://open.weixin.qq.com/connect/oauth2/authorize";
	/**
	 * 通过code换取网页授权access_token
	 */
	public static String URL_OAUTH2_ACCESS_TOKEN = "https://api.weixin.qq.com/sns/oauth2/access_token";
	/**
	 * access_token
	 */
	public static String URL_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token";

	
	/**
	 *万卡优选公众号的appId 
	 */
	public static String APPID_MARKET =  "wx7b59340d20d8ef77";
	
	/**
	 * 万卡优选公众号的AppSecret(应用密钥) 
	 */
	public static String APPSECRET_MARKET = "13ecea5da95e0d4dc4dc1ee9688f639b";
	
	/**
	 * 静默授权
	 */
	public static String SCOPE_BASE = "snsapi_base";
	/**
	 * 用户已关注公众号也是静默授权
	 */
	public static String SCOPE_USERINFO = "snsapi_userinfo";

	/**
	 * JSSDK:grant_type
	 */
	public static final String JSSDK_GRANT_TYPE = "client_credential";

	/**
	 * JSSDK:access_token获取地址
	 */
	public static final String URL_JSSDK_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token";
	
	/**
	 * 下载多媒体文件地址
	 */
	public static final String RUL_MEDIA_DOWNLOAD = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
	

	/**
	 * JSSDK:jsapi_ticket获取地址
	 */
	public static final String URL_JSSDK_JSAPI_TICKET = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";


	/**
	 * jsapi_ticket规则
	 */
	public static String jsapiTicketUrl = URL_JSSDK_JSAPI_TICKET
			+ "?access_token=" + URL_OAUTH2_ACCESS_TOKEN
			+ "&type=jsapi";

	/**
	 * 获取静默授权链接
	 * @author ducongcong
	 * @param appId 
	 * @createDate 2016年5月24日
	 * @updateDate 
	 * @param proId
	 * @return
	 */
	public static String getOAuthBase(String appId,String redirect_uri){
		return getOAuthUrl(SCOPE_BASE,appId,redirect_uri);
	}
	/**
	 * 获取用户确定授权连接（已关注也是静默授权）
	 * @author ducongcong
	 * @createDate 2016年5月24日
	 * @updateDate 
	 * @param proId
	 * @return
	 */
	public static String getOAuthUserInfo(String appId,String redirect_uri){
		return getOAuthUrl(SCOPE_USERINFO,appId,redirect_uri);
	}
	public static String getOAuthUrl(String scope, String appId,String redirect_uri) {
		StringBuffer sb = new StringBuffer();
		try {
			sb.append(URL_OAUTH2_AUTHORIZE)
			  .append("?appid=").append(appId)
			  .append("&redirect_uri=").append(URLEncoder.encode(redirect_uri, "UTF-8"))
			  .append("&response_type=code")
			  .append("&scope=").append(scope)
			  .append("&state=").append(getEncode(System.currentTimeMillis()+""))
			  .append("#wechat_redirect")
			  ;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
	public static String getEncode(String str){
		String USER_SALT="pVrG+nGlxU4amKi39E6bTA==";
		if(str!=null){
			return EncryptUtil.getInstance().AESencode(str, USER_SALT);
		}
		return null;
	}
	/**
	 * 获取微信访问token并校验时间
	 * @author ducongcong
	 * @createDate 2016年5月24日
	 * @updateDate 
	 * @param code
	 * @param state
	 * @param appecret 
	 * @param appId 
	 * @return
	 */
	public static ResultData getAccessToken(String code,String state, String appId, String appSecret){
		ResultData resultData = null;
		String proId = "";
		if(StringUtils.isNotEmpty(state)){
			long decode = Long.parseLong(state);
			if((System.currentTimeMillis()-decode)/1000 > 100){
				resultData = ResultDataUtil.errorResult("该链接已失效，请重新再试！");
				return resultData;
			}
		}else{
			resultData = ResultDataUtil.errorResult("数据异常！");
			return resultData;
		}
		Map<String, String> params = new HashMap<String, String>();
		params.put("appid", appId);
		params.put("secret", appSecret);
		params.put("code", code);
		params.put("grant_type", "authorization_code");
		try {
			String sendPost = HttpUtils.sendPost(URL_OAUTH2_ACCESS_TOKEN, params);
			if(StringUtils.isNotEmpty(sendPost) && sendPost.contains("access_token")){
				WeixinVo weixinVo = GsonUtil.fromJson(sendPost, WeixinVo.class);
				weixinVo.setProId(proId);
				resultData = ResultDataUtil.successResult("获取数据成功", weixinVo);
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultData = ResultDataUtil.errorResult("系统异常，请稍后再试");
		}
		return resultData;
	}
	/**
	 * 获取微信访问token并校验时间
	 * @author ducongcong
	 * @createDate 2016年5月24日
	 * @updateDate 
	 * @param code
	 * @param state
	 * @param appecret 
	 * @param appId 
	 * @return
	 */
	public static ResultData getAccessToken(String appId, String appSecret){
		ResultData resultData = null;
		Map<String, String> params = new HashMap<String, String>();
		params.put("appid", appId);
		params.put("secret", appSecret);
		params.put("grant_type", "client_credential");
		try {
			String sendPost = HttpUtils.sendPost(URL_ACCESS_TOKEN, params);
			resultData = ResultDataUtil.successResult("获取数据成功", sendPost);
		} catch (Exception e) {
			e.printStackTrace();
			resultData = ResultDataUtil.errorResult("系统异常，请稍后再试");
		}
		return resultData;
	}
	public static String getCode(String url){

		String sendPost = "";
		try {
			sendPost = HttpUtils.sendGet2(url);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sendPost;
	}

	
//	public static String getPropertiesAPPID(){
//		Boolean model = PropKit.getBoolean(ConstantConfig.CONFIG_INTERFACE_MODEL,false);
//		if(model){
//			return APPID;
//		}else{
//			return APPID_TEST;
//		}
//	}
//	
//	public static String getPropertiesAppSecret(){
//		Boolean model = PropKit.getBoolean(ConstantConfig.CONFIG_INTERFACE_MODEL,false);
//		if(model){
//			return APPSECRET;
//		}else{
//			return APPSECRET_TEST;
//		}
//	}
}
